package com.vehiclemanagement.filter;

import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Swagger参数过滤器
 * 用于处理Swagger API请求中的空字符串默认值问题
 */
@Component
public class SwaggerParameterFilter extends OncePerRequestFilter {

    private static final String SWAGGER_URL = "/v2/api-docs";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        String requestURI = request.getRequestURI();
        
        // 只处理Swagger API文档请求
        if (requestURI.contains(SWAGGER_URL)) {
            filterChain.doFilter(new SwaggerParameterRequestWrapper(request), response);
        } else {
            filterChain.doFilter(request, response);
        }
    }

    /**
     * 自定义请求包装器，用于处理Swagger参数
     */
    private static class SwaggerParameterRequestWrapper extends HttpServletRequestWrapper {
        
        public SwaggerParameterRequestWrapper(HttpServletRequest request) {
            super(request);
        }

        @Override
        public String getParameter(String name) {
            String value = super.getParameter(name);
            // 处理空字符串默认值，转换为null
            if ("".equals(value)) {
                return null;
            }
            return value;
        }

        @Override
        public Map<String, String[]> getParameterMap() {
            Map<String, String[]> parameterMap = new HashMap<>(super.getParameterMap());
            
            // 处理所有空字符串参数值
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                String[] values = entry.getValue();
                if (values != null) {
                    for (int i = 0; i < values.length; i++) {
                        if ("".equals(values[i])) {
                            values[i] = null;
                        }
                    }
                }
            }
            
            return Collections.unmodifiableMap(parameterMap);
        }

        @Override
        public Enumeration<String> getParameterNames() {
            return super.getParameterNames();
        }

        @Override
        public String[] getParameterValues(String name) {
            String[] values = super.getParameterValues(name);
            if (values != null) {
                for (int i = 0; i < values.length; i++) {
                    if ("".equals(values[i])) {
                        values[i] = null;
                    }
                }
            }
            return values;
        }
    }
} 